function RemoveArray(array, attachId) {
	var f = false;
	for (var i = 0, n = 0; i < array.length; i++) {
		if (array[i] != attachId) {
			array[n++] = array[i];
		} else
			f = true;
	}
	if (f == true)
		array.length -= 1;
}

Array.prototype.remove = function(obj) {
	return RemoveArray(this, obj);
};

var $J = jQuery.noConflict();

var photo_ds;
var category_ds;

function getPrePhoto(id) {
	for (var i = 1; i < photo_ds.length; i++) {
		var p = photo_ds[i];
		if (p.id == id) {
			return photo_ds[i - 1];
		}
	}
}
function getPhoto(id){
	for (var i = 0; i < photo_ds.length; i++) {
		var p = photo_ds[i];
		if (p.id == id) {
			return photo_ds[i];
		}
	}
}
function getNextPhoto(id) {
	for (var i = 0; i < photo_ds.length - 1; i++) {
		var p = photo_ds[i];
		if (p.id == id) {
			return photo_ds[i + 1];
		}
	}
}

function removePhotofromDS(id) {
	for (var i = 0; i < photo_ds.length; i++) {
		var p = photo_ds[i];
		if (p.id == id) {
			photo_ds.remove(p);
		}
	}

}
function getCategory(code){
		for (var i = 0; i < category_ds.length; i++) {
		var p = category_ds[i];
		if (p.code == code) {
			return category_ds[i];
		}
	}
}

function upgradePhotofromDS(id, preId) {
	var idx, preIdx;
	for (var i = 0; i < photo_ds.length; i++) {
		var p = photo_ds[i];
		if (p.id == id) {
			idx = i;
		}
		if (p.id == preId) {
			preIdx = i;
		}
	}
	var temp = photo_ds[idx];
	photo_ds[idx] = photo_ds[preIdx];
	photo_ds[preIdx] = temp;
}
function getPhotoCategoryHTML(categories) {
	var html = '';
	for (var i = 0; i < categories.length; i++) {
		var category = categories[i];
		html += '<div class="category" id="' + category.code + '">'
				+ category.name + '(<span id=category_' + category.code
				+ '></span>)</div>';
	}
	return html;
}

function getPhotoHTML(photos) {
	var html = '';
	for (var i = 0; i < photos.length; i++) {
		var photo = photos[i];
		html += '<div class="picList">' + photo.fileName + '<br/>'
				+ '<img id="thumbnail" src=../' + photo.thumbnailUrl
				+ ' photoID=' + photo.id + '><br/>' + '<a href="#" id='
				+ photo.id + '>删除</a>  <a href="#" id=' + photo.id
				+ '>升序</a>	<br/>' +(photo.verified?'已验证照片': '<a href="#" id=' + photo.id+'>设置为验证照片</a>')+'</div>';
	}
	return html;
}

function blockUploading(event) {
	if(validate()){
	$J.unblockUI();

	$J.blockUI({
		message : '文件上传中，请稍候...',
		css : {
			border : 'none',
			padding : '15px',
			backgroundColor : '#000',
			'-webkit-border-radius' : '10px',
			'-moz-border-radius' : '10px',
			opacity : '.5',
			color : '#fff'
		}
	});
	}
	else{
		event.preventDefault();
	}
	
}

function getCategorySelection() {
	var html = '';
	for (var i = 0; i < category_ds.length; i++) {
		var category = category_ds[i];
		html += '<option value=' + category.code + '>' + category.name
				+ '</option>';
	}
	return html;
}

function loadPhotoCount() {
	for (var i = 0; i < category_ds.length; i++) {
		var category = category_ds[i];
		var code = category.code;
		_loadPhotoCount(code,i);
	}
}

function _loadPhotoCount(code,i) {
	PhotoService.getTotalCountyCategoryCode(code, function(ret) {
		var category=getCategory(code);
		category.totalCount=ret;
		$J("div span#category_" + code)[0].innerText = ret;
		if(i==0)
		$J("div.category#" + code).trigger('click');
	});
}
function loadCategory() {

	PhotoCategoryService.getAllPhotoCategoryByUserNo(function(categories) {
		category_ds = categories;
		var firstId;
		if (categories && categories.length > 0) {
			firstId = categories[0].code;
		}
		var html = getPhotoCategoryHTML(categories);
		$J("#photo_category_data").html(html);

		bindEvent();
		loadPhotoCount();
		

	});
}

function generateMostPopPicHTML(photos){
	var html='';
	
	for(var i=0;i<photos.length;i++){
		var photo=photos[i];
		html+='<div style="text-align: center; margin-top: 10px;">'
		+photo.fileName+'<br/><img style="width: 100px;height: 100px;border: 0;" src=../'
		+photo.thumbnailUrl+'></div>';
	}
	return html;
}
//载入最受欢迎照片
function loadMostPopularPic(userNo){
	PhotoService.getTopPhoto(10000,5,function(ret){
		$J("#mostpopid").html(generateMostPopPicHTML(ret));
	})
}

function loadPhoto(code,pageIndex) {
	$J("#photoView").hide();
	$J("#photoviewer").hide();
	
	$J("#thumbnailView").show();
	$J("#mostpopularpic").show();
	
	var totalCount=getCategory(code).totalCount;
	var iTotalCount=parseInt(totalCount);
	var pageCount=iTotalCount/20;
	if(iTotalCount%20>0){
		pageCount++;
	}
	var pagingHTML='';
	for(var i=1;i<=pageCount;i++){
		pagingHTML+='<a href="javascript:loadPhoto('+code+','+(i-1)+')">'+i+'</a>&nbsp;'
	}
	$J("div#paging").html(pagingHTML);
	PhotoService.getPhotoByCategoryCode(code, (pageIndex||0)*20, 20, function(photos) {
		photo_ds = photos;
		var html = getPhotoHTML(photos);
		$J('#photo_data').html(html);
		bindPhotoEvent();
	})
}

function addCategory() {
	var category = {};
	category.name = $J("#categoryName").val();
	category.isPublic = $J("#isPublic").attr("checked");
	// alert(category.name);
	// alert(category.isPublic);
	PhotoCategoryService.saveOrUpdatePhotoCategory(category, function() {
		loadCategory();
		$J.unblockUI();
	})

}
function bindEvent() {
	// 点击相册事件绑定
	$J('div.category').click(function(event) {
		var e = event.target;
		var code = e.id;
		loadPhoto(code);
	});
	// 添加相册事件绑定
	$J("#add_category").click(function(event) {
		$J.blockUI({
			message : '<div style="valign:middle">'
					+ '相册名称：<input type=text id="categoryName"/><br />'
					+ '是否公开：<input type=checkbox id="isPublic" checked=true/><br />'
					+ '<input type=submit value=确定 onclick="addCategory()"><input type=submit value=取消 onclick="$J.unblockUI();"></div>',
			css : {
				border : 'none',
				padding : '15px',
				'-webkit-border-radius' : '10px',
				'-moz-border-radius' : '10px',
				opacity : '.5',
				cursor : 'pointer'
			}
		})
	});

	$J("#upload_photo").click(function() {
		$J("#categorySelect").html(getCategorySelection());
		$J.blockUI({
			message : $J("#uploadFormDiv"),
			css:{
			 cursor:'pointer',
			 '-webkit-border-radius' : '10px',
			'-moz-border-radius' : '10px',
			opacity : '.5'
			}

		})
	});
	$J("#del_category").click(function() {
		$J.blockUI({
			message : '<iframe src=photo.jsp height=200px width=100% frameborder=0/>',
			css:{
			 cursor:'pointer',
			 '-webkit-border-radius' : '10px',
			'-moz-border-radius' : '10px',
			opacity : '.5'
			}

		})
	});
}

function delPhoto(id) {
	PhotoService.removePhoto(id, function() {
		/*
		 * alert(id); alert($J("div.picList a#"+id)[0]); alert($J("div.picList
		 * a#"+id)[0].parentNode);
		 */
		var photoDiv = $J("div.picList a#" + id)[0].parentNode;
		removePhotofromDS(id);
		photoDiv.parentNode.removeChild(photoDiv);
	})
}
function verifyPhoto(id) {
	PhotoService.verifyPhoto(id, function() {
		var photo=getPhoto(id);
		var categoryCode=photo.categoryCode;
		loadPhoto(categoryCode);
	})
}

function upgradePhoto(id, preId) {
	PhotoService.upgradePhoto(id, preId, function() {
		upgradePhotofromDS(id, preId);
		var photoDiv = $J("div.picList a#" + id)[0].parentNode;
		var prePhotoDiv = $J("div.picList a#" + preId)[0].parentNode;
		var p = photoDiv.parentNode;
		p.insertBefore(photoDiv, prePhotoDiv);
	});
}

function showPhoto(event) {
	$J("#photoView").show();
	$J("#photoviewer").show();
	
	$J("#thumbnailView").hide();
	$J("#mostpopularpic").hide();
	
	var e = event.target;
	var id = e.photoID;
	PhotoService.increaseViewCount(id);
	/*
	 * var pre = e.parentNode.previousSibling; $J("div.picList#pre").html('');
	 * if (pre) { $J("div.picList#pre").append(pre.childNodes[0]);
	 * $J("div.picList#pre").append(pre.childNodes[1]); //
	 * $J("div.picList#pre").append(pre.childNodes[2]); }
	 */
	var prePhoto = getPrePhoto(id);
	var prePhotoHTML = '';
	if (prePhoto) {
		prePhotoHTML = '<div class="picList">' + prePhoto.fileName + '<br/>'
				+ '<img id="thumbnail" src=../' + prePhoto.thumbnailUrl
				+ ' photoID=' + prePhoto.id + '>';
	}
	$J("div.picList#pre").html(prePhotoHTML);

	var nextPhoto = getNextPhoto(id);
	var nextPhotoHTML = '';
	if (nextPhoto) {
		nextPhotoHTML = '<div class="picList">' + nextPhoto.fileName + '<br/>'
				+ '<img id="thumbnail" src=../' + nextPhoto.thumbnailUrl
				+ ' photoID=' + nextPhoto.id + '>';
	}
	$J("div.picList#next").html(nextPhotoHTML);

	$J("#thumbnailView").removeClass('show').addClass('hidden');
	var thumbnailUrl = e.src;
	var photoUrl = thumbnailUrl.replace('thumbnail/', 'photo');
	var html = '<img src="' + photoUrl + '">';
	$J("div.photo").html(html);
	$J("#photoView").removeClass('hidden').addClass('show');
	// bindPrePhoto,NextPhoto
	// alert($J("div#pre img")[0].src);
	$J("div#pre img").click(showPhoto);
	$J("div#next img").click(showPhoto);
}
function bindPhotoEvent() {

	// 绑定删除照片事件

	$J("div.picList a:nth-child(4)").click(function(event) {
		var e = event.target;
		var id = e.id;
		delPhoto(id);
		event.preventDefault();
	});

	// 綁定升序事件
	// alert($J("div.picList a:nth-child(5)").size());
	$J("div.picList a:nth-child(5)").click(function(event) {
		var e = event.target;
		var pre = e.parentNode.previousSibling;
		// 空白（空格）也是Node
		var preId = pre.childNodes[4].id;
		var id = e.id;
		upgradePhoto(id, preId);
		event.preventDefault();
	});

	// 綁定验证事件

	$J("div.picList a:nth-child(7)").click(function(event) {
		var e = event.target;
		var id = e.id;
		verifyPhoto(id);
		event.preventDefault();
	});

	// 绑定点击照片事件
	$J("div.picList img").click(showPhoto);
}

function validate() {
	var allowedTypes = ['jpg', 'gif', 'png'];
	var flag = true;
	$J(":file").each(function() {
		var fileName = this.value;
		if (fileName) {
			var idx = fileName.lastIndexOf('.');
			var sufix = fileName.substring(idx + 1);
			for (var i = 0; i < allowedTypes.length; i++) {
				if (sufix == allowedTypes[i]) {
					return ;
				}
			}
			alert(fileName + " 格式不对.\n只支持jpg,gif,png.");
			flag = false;
		}
	});
	return flag;
}
function showResult(msg) {
	loadCategory();
	
	 $J.unblockUI();
	 alert(msg);
}

$J(function() {
	$J("#photoView").hide();
	$J("#photoviewer").hide();
	
	$J("#thumbnailView").show();
	$J("#mostpopularpic").show();
	
	$J("#uploadForm").bind('submit', blockUploading);
});

$J(loadCategory);
$J(loadMostPopularPic);

